package ru.agiledev.akb.server.util;


import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * Created by a.kirillov
 * Date: 5/14/11 Time: 3:29 PM
 */
public class MailManager {
    public static void postMail(String name, String pwd, String sendTo) throws MessagingException, javax.mail.MessagingException {
        String host = "smtp.gmail.com";
        String from = "aspectsearch.adm@gmail.com";
        String pass = "7ru57_n0_1";

        Properties props = System.getProperties();

        props.put("mail.smtp.starttls.enable", "true"); // added this line
        props.put("mail.smtp.port", 587);
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        //props.put("mail.smtp.socketFactory.port", 465);

//        'mail.smtp.socketFactory.class': 'javax.net.ssl.SSLSocketFactory',
//        'mail.smtp.socketFactory.fallback': 'false'




        props.put("mail.smtp.auth", "true");

        String[] to = {sendTo}; // added this line

        Session session = Session.getDefaultInstance(props, new GMailAuthenticator(from, pass));
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));

        InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of addresses
        for( int i=0; i < to.length; i++ ) { // changed from a while loop
            toAddress[i] = new InternetAddress(to[i]);
        }

        // To get the array of addresses
        for( int i=0; i < to.length; i++ ) { // changed from a while loop
            toAddress[i] = new InternetAddress(to[i]);
        }

        for( int i=0; i < toAddress.length; i++) { // changed from a while loop
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
        }
        message.setSubject("Восстановление пароля");
        message.setText("Здравствуйте,"+name+".\n" +
                "Вы получили это письмо от администратора Аспектно-Ориентированной Базы Знаний.\n\n\n" +
                "Ваш новый пароль: "+pwd+"\n\n" +
                "Вы можете выполнить вход, используя данный пароль, а затем изменить его в настройках профиля пользователя.\n\n\n" +
                "--\nС Уважением,\nадминистратор АОБЗ");

        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

    }



    public static void main(String[] args){
        try {
            postMail("Вася", "adsfdsaf", "antonv.kirillov@gmail.com");
        } catch (MessagingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public static class GMailAuthenticator extends Authenticator {
        String user;
        String pw;
        public GMailAuthenticator (String username, String password)
        {
            super();
            this.user = username;
            this.pw = password;
        }
        public PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(user, pw);
        }
    }

}
